<template>
  <div class="trace-image-generator">
    <!-- 调试信息 -->
    <div v-if="loading" class="debug-info">
      <p>正在加载数据...</p>
      <p>ID: {{ route.query.id }}</p>
    </div>

    <!-- 溯源图片 -->
    <div class="trace-card" ref="traceCardRef">
      <!-- 左侧产品图片区域 -->
      <div class="product-image-section">
        <div class="product-image-wrapper">
          <div v-if="loading || imageLoading" class="placeholder-image">
            <div class="loading-spinner">⏳</div>
            <div>{{ loading ? '加载中...' : '图片加载中...' }}</div>
          </div>
          <img v-else-if="data && (data.fullImageUrl || data.coverImageUrl)"
               :src="data.fullImageUrl || getFullImageUrl(data.coverImageUrl)"
               alt="产品图片"
               class="product-main-image"
               @load="handleImageLoad"
               @error="handleImageError" />
          <div v-else class="placeholder-image">
            <div class="no-image-icon">📷</div>
            <div>暂无图片</div>
          </div>
        </div>
      </div>

      <!-- 右侧信息区域 -->
      <div class="product-info-section">
        <!-- 右上角按钮区域 -->
        <div class="top-actions">
          <button class="action-btn" @click="editProductionInfo">修改基本信息</button>
          <button class="action-btn" @click="exportTraceCode" :disabled="exportLoading">
            {{ exportLoading ? '导出中...' : '导出溯源' }}
          </button>
        </div>

        <!-- 产品标题 -->
        <div class="product-title-section">
          <h1 class="product-name">{{ data?.goodsName || '兔头 (麻辣味)' }}</h1>
        </div>

        <!-- 产品信息网格 -->
        <div class="product-info-grid">
          <div class="info-row">
            <div class="info-item">
              <span class="label">生产批次：</span>
              <span class="value">{{ data?.batchNumber || '20210718' }}</span>
            </div>
            <div class="info-item">
              <span class="label">保质期：</span>
              <span class="value">{{ data?.shelfLifeDays || '90' }}天</span>
            </div>
          </div>

          <div class="info-row">
            <div class="info-item">
              <span class="label">生产许可证号：</span>
              <span class="value">{{ data?.productionLicenseNumber || 'SC213205427680' }}</span>
            </div>
            <div class="info-item">
              <span class="label">生产企业：</span>
              <span class="value">{{ data?.manufacturerName || '成都爱吃兔食品加工有限公司' }}</span>
            </div>
          </div>
        </div>

        <!-- 产品检验报告区域 -->
        <div class="inspection-section">
          <div class="inspection-header">
            <span class="inspection-title">产品检验报告</span>
          </div>

          <div class="inspection-content">
            <!-- 加载状态 -->
            <div v-if="inspectionImagesLoading" class="inspection-loading">
              <div class="loading-spinner">⏳</div>
              <div class="loading-text">正在加载检验报告图片...</div>
            </div>
            
            <!-- 已上传的检验报告文档 -->
            <div v-else v-for="(image, index) in inspectionImages" :key="index" class="inspection-document">
              <div class="document-preview">
                <img :src="image.url" :alt="`检验报告${index + 1}`" class="inspection-image" />
                <div class="close-btn" @click="removeInspectionImage(index)">×</div>
              </div>
            </div>

            <!-- 添加按钮 -->
            <el-upload
              class="inspection-upload"
              action="http://localhost:34405/api/Image/upload-with-info"
              :show-file-list="false"
              :on-success="handleInspectionImageSuccess"
              :on-error="handleInspectionImageError"
              :on-progress="handleInspectionUploadProgress"
              :before-upload="beforeInspectionUpload"
              :data="getUploadData"
              name="file"
              accept="image/*"
              method="post"
              :headers="uploadHeaders"
            >
              <div class="add-document">
                <div class="add-btn" v-if="inspectionUploadProgress === 0">
                  <span class="plus-icon">+</span>
                </div>
                <div class="upload-progress-mini" v-else>
                  <div class="progress-circle-mini">{{ inspectionUploadProgress }}%</div>
                </div>
              </div>
            </el-upload>

            <!-- 信息徽章 -->
            <div class="info-badge">
              <span class="badge-number">{{ inspectionImages.length }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 底部导航标签 -->
    <div class="bottom-navigation">
              <div class="nav-tabs">
            <div class="nav-tab" @click="navigateToBreeding" :class="{ 'active': showBreeding }">
              <span class="tab-text">养殖信息 </span>
            </div>
            <div class="nav-tab" @click="navigateToSlaughter" :class="{ 'active': showSlaughter }">
              <span class="tab-text">屠宰信息 </span>
            </div>
            <div class="nav-tab" @click="navigateToProcessing" :class="{ 'active': showProcessing }">
              <span class="tab-text">深加工信息 </span>
            </div>
          </div>
    </div>

    <!-- 养殖信息子组件容器 -->
    <div v-if="showBreeding" class="breeding-component-container">
      <Breeding :batchNumber="data?.batchNumber || ''" />
    </div>

    <!-- 屠宰信息子组件容器 -->
    <div v-if="showSlaughter" class="breeding-component-container">
      <Slaughter :batchNumber="data?.batchNumber || ''" />
    </div>

    <!-- 深加工信息子组件容器 -->
    <div v-if="showProcessing" class="breeding-component-container">
      <div class="processing-info-placeholder">
        <div class="placeholder-icon">📝</div>
        <div class="placeholder-text">深加工信息组件尚未实现</div>
      </div>
    </div>
 

    <!-- 修改对话框 -->
    <div v-if="showEditDialog" class="dialog-overlay" @click="closeEditDialog">
      <div class="dialog-content" @click.stop>
        <div class="dialog-header">
          <h3>修改生产信息</h3>
          <button class="close-button" @click="closeEditDialog">×</button>
        </div>
        <div class="dialog-body">
          <div class="form-row">
            <div class="form-label">
              <span class="required">*</span>商品名称：
            </div>
            <div class="form-input">
              <select v-model="formData.goodsId" class="form-select" :disabled="goodsLoading">
                <option value="0" disabled>{{ goodsLoading ? '加载中...' : '请选择商品' }}</option>
                <option v-for="item in goodsList" :key="item.goodsId" :value="item.goodsId">
                  {{ item.goodsName }}
                </option>
              </select>
            </div>
          </div>

          <div class="form-row">
            <div class="form-label">
              <span class="required">*</span>生产批次：
            </div>
            <div class="form-input">
              <input type="text" v-model="formData.batchNumber" placeholder="请输入生产批次" />
            </div>
          </div>

          <div class="form-row">
            <div class="form-label">
              <span class="required">*</span>保质期（天）：
            </div>
            <div class="form-input">
              <input type="number" v-model="formData.shelfLifeDays" placeholder="请输入保质期天数" min="1" />
            </div>
          </div>

          <div class="form-row">
            <div class="form-label">生产许可证号：</div>
            <div class="form-input">
              <input type="text" v-model="formData.productionLicenseNumber" placeholder="请输入生产许可证号" />
            </div>
          </div>

          <div class="form-row">
            <div class="form-label">
              <span class="required">*</span>生产企业：
            </div>
            <div class="form-input">
              <input type="text" v-model="formData.manufacturerName" placeholder="请输入生产企业" />
            </div>
          </div>

          <!-- 图片上传 -->
          <div class="image-upload-section">
            <div class="form-label">
              <span class="required">*</span>产品图片：
            </div>
            <div class="image-upload-content">
              <el-upload
                class="upload-demo"
                action="http://localhost:34405/api/Image/upload"
                :show-file-list="false"
                :on-success="handleEditImgSuccess"
                :on-error="handleError"
                :on-progress="handleUploadProgress"
                :before-upload="beforeUpload"
                name="file"
                accept="image/*"
                method="post"
                :headers="uploadHeaders"
              >
                <div v-if="!editForm.picture" class="upload-placeholder">
                  <div v-if="uploadProgress > 0" class="upload-progress">
                    <div class="progress-circle">{{ uploadProgress }}%</div>
                    <div class="progress-text">上传中...</div>
                  </div>
                  <div v-else class="upload-content">
                    <div class="upload-icon">📷</div>
                    <div class="upload-text">点击上传图片</div>
                    <div class="upload-hint">支持 JPG、PNG、GIF、BMP、WEBP 格式，大小不超过 5MB</div>
                  </div>
                </div>
                <div v-else class="image-preview">
                  <img :src="editForm.picture" class="preview-image" alt="产品图片" />
                  <div class="image-overlay">
                    <span class="change-text">点击更换图片</span>
                  </div>
                </div>
              </el-upload>
              <div v-if="editForm.picture" class="image-info">
                <div class="image-url">
                  <span class="url-label">图片地址：</span>
                  <a :href="editForm.picture" target="_blank" class="url-link">{{ editForm.picture }}</a>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="dialog-footer">
          <button class="submit-button" @click="submitEditForm">保存</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, computed, watch } from 'vue'
import { useRoute } from 'vue-router'
import { apiWreit } from '@/Ulter/AxiosHepler'
import { ElMessage } from 'element-plus'
import * as XLSX from 'xlsx'
// 导入Breeding组件
import Breeding from '@/components/Traceability/Breeding.vue'
import Slaughter from '@/components/Traceability/Slaughter.vue'
const route = useRoute()

// 控制养殖信息组件显示状态
const showBreeding = ref(false)

// 控制屠宰信息组件显示状态
const showSlaughter = ref(false)

// 控制深加工信息组件显示状态
const showProcessing = ref(false)

// 导航到养殖信息组件
const navigateToBreeding = () => {
  showBreeding.value = true
  showSlaughter.value = false
  showProcessing.value = false
  console.log('显示养殖信息组件')
}

// 导航到屠宰信息组件
const navigateToSlaughter = () => {
  showBreeding.value = false
  showSlaughter.value = true
  showProcessing.value = false
  console.log('显示屠宰信息组件')
}

// 导航到深加工信息组件
const navigateToProcessing = () => {
  showBreeding.value = false
  showSlaughter.value = false
  showProcessing.value = true
  console.log('显示深加工信息组件')
}








const data = ref<any>(null)









const goodsName = ref<string>('兔头（麻辣味）') // 设置默认值防止null错误
const loading = ref(true)
const traceCardRef = ref<HTMLElement>()

// 修改功能相关变量
const showEditDialog = ref(false)
const goodsList = ref<any[]>([])
const goodsLoading = ref(false)

// 导出功能相关变量
const exportLoading = ref(false)

// 图片加载状态
const imageLoading = ref(false)
const uploadProgress = ref(0)

// 检验报告图片相关
const inspectionImages = ref<Array<{url: string, imageBatch: string, traceStage: string, traceType: string}>>([])
const inspectionUploadProgress = ref(0)
const inspectionImagesLoading = ref(false)

// 图片缓存
const imageCache = new Map<string, boolean>()

// 表单数据
const formData = reactive({
  id: '' as string | number,
  batchNumber: '',
  shelfLifeDays: 0,
  productionLicenseNumber: '',
  manufacturerName: '',
  coverImageUrl: null as string | null,
  goodsId: 0
})

// 图片上传相关
const editForm = ref({
  picture: ''
})

// 上传headers
const uploadHeaders = computed(() => {
  const token = localStorage.getItem('token')
  return token ? { 'Authorization': `Bearer ${token}` } : {}
})

// 获取商品列表
const getGoodsList = async () => {
  goodsLoading.value = true

  try {
    const response = await apiWreit.get('/api/Mange/GetGoods/goods')

    if (response.status === 200 && response.data && Array.isArray(response.data.data)) {
      goodsList.value = response.data.data
      console.log('成功获取商品列表:', goodsList.value.length, '条记录')
    } else {
      console.warn('API返回的商品数据格式不正确或为空')
      goodsList.value = []
    }
  } catch (err: any) {
    console.error('获取商品列表失败:', err)
    goodsList.value = []
  } finally {
    goodsLoading.value = false
  }
}

// 处理图片上传成功
const handleEditImgSuccess = (response: any) => {
  console.log('上传响应:', response)
  if (response && response.data) {
    const imageUrl = response.data

    // 使用统一的图片URL处理函数
    const fullImageUrl = getFullImageUrl(imageUrl);
    editForm.value.picture = fullImageUrl;

    // 保存原始的相对路径到formData，用于提交到后端
    formData.coverImageUrl = imageUrl;

    console.log('图片上传成功 - 原始URL:', imageUrl);
    console.log('图片上传成功 - 完整URL:', fullImageUrl);

    // 重置上传进度
    uploadProgress.value = 0;

    ElMessage.success('图片上传成功！');
  } else {
    console.error('上传失败，响应格式异常:', response);
    ElMessage.error('上传失败，未返回图片地址');
  }
}

// 处理上传进度
const handleUploadProgress = (event: any) => {
  if (event.percent !== undefined) {
    uploadProgress.value = Math.round(event.percent);
    console.log('上传进度:', uploadProgress.value + '%');
  }
}

// 处理上传错误
const handleError = (error: any) => {
  console.error('上传错误:', error)
  uploadProgress.value = 0;
  ElMessage.error('上传失败，请检查网络或服务器状态')
}

// 上传前的验证
const beforeUpload = (file: any) => {
  console.log('开始验证上传文件:', file);

  // 检查文件是否存在
  if (!file) {
    ElMessage.error('请选择要上传的文件!');
    return false;
  }

  // 检查文件类型
  const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/bmp', 'image/webp'];
  const isImage = allowedTypes.includes(file.type);
  if (!isImage) {
    ElMessage.error('只能上传JPG/PNG/GIF/BMP/WEBP格式的图片!');
    console.error('不支持的文件类型:', file.type);
    return false;
  }

  // 检查文件大小（限制为5MB）
  const maxSize = 5 * 1024 * 1024; // 5MB
  if (file.size > maxSize) {
    ElMessage.error('图片大小不能超过5MB!');
    console.error('文件过大:', file.size, '字节');
    return false;
  }

  // 检查图片尺寸（可选）
  return new Promise((resolve) => {
    const img = new Image();
    img.onload = () => {
      const width = img.width;
      const height = img.height;
      console.log('图片尺寸:', width, 'x', height);

      // 可以在这里添加尺寸限制
      if (width > 4000 || height > 4000) {
        ElMessage.warning('图片尺寸较大，可能影响加载速度');
      }

      resolve(true);
    };
    img.onerror = () => {
      ElMessage.error('图片文件损坏，请重新选择!');
      resolve(false);
    };
    img.src = URL.createObjectURL(file);
  });
}

// 提交修改表单
const submitEditForm = async () => {
  // 基本验证
  if (!formData.goodsId || !formData.batchNumber || formData.shelfLifeDays <= 0) {
    ElMessage.warning('请填写必填项')
    return
  }

  try {
    const payload = {
      ...formData,
      ModifiedBy: localStorage.getItem('username') || 'system'
    }

    const response = await apiWreit.put(`/api/ProductionUpdate`, payload)
    if (response && response.status === 200) {
      ElMessage.success('修改成功')
      showEditDialog.value = false
      // 重新获取数据
      getProductionInfo()
    }
  } catch (error) {
    console.error('修改失败:', error)
    ElMessage.error('修改失败')
  }
}

// 关闭修改对话框
const closeEditDialog = () => {
  showEditDialog.value = false
}

// 获取生产信息详情
const getProductionInfo = async () => {
  const id = route.query.id as string
  console.log('获取到的ID参数:', id)

  if (!id) {
    console.warn('没有获取到ID参数')
    loading.value = false
    return
  }

  try {
    loading.value = true

    // 先获取商品列表
    console.log('开始获取商品列表...')
    const goodsResponse = await apiWreit.get('/api/Mange/GetGoods/goods')
    let goodsList: any[] = []
    if (goodsResponse.status === 200 && goodsResponse.data?.data) {
      goodsList = goodsResponse.data.data
      console.log('商品列表获取成功:', goodsList.length, '条')
    }

    // 再获取生产信息详情
    console.log('开始获取生产信息详情...')
    const response = await apiWreit.get(`/api/ProductionUpdate/${id}`)
    console.log('生产信息API响应:', response)

    if (response.status === 200 && response.data) {
      data.value = response.data.data || response.data
      console.log('获取到的生产信息数据:', data.value)

      // 检查并处理图片URL
      if (data.value?.coverImageUrl) {
        // 智能处理图片URL
        let fullImageUrl = '';
        if (data.value.coverImageUrl.startsWith('http://') || data.value.coverImageUrl.startsWith('https://')) {
          // 如果是完整URL，直接使用
          fullImageUrl = data.value.coverImageUrl;
        } else {
          // 如果是相对路径，则添加服务器地址
          fullImageUrl = `http://localhost:34405${data.value.coverImageUrl}`;
        }
        console.log('处理后的图片URL:', fullImageUrl);

        // 更新数据中的图片URL为完整URL，便于后续使用
        data.value.fullImageUrl = fullImageUrl;

        // 设置图片加载状态并预加载图片
        imageLoading.value = true;
        preloadImage(fullImageUrl).then((success) => {
          imageLoading.value = false;
          if (success) {
            console.log('主图片预加载完成');
          } else {
            console.warn('主图片预加载失败，可能影响显示效果');
          }
        });
      }

      // 根据goodsId查找商品名称
      if (data.value?.goodsId && goodsList.length > 0) {
        const goods = goodsList.find((item: any) => item.goodsId === data.value.goodsId)
        if (goods?.goodsName) {
          goodsName.value = goods.goodsName
          console.log('找到商品名称:', goods.goodsName)
        } else {
          console.warn('未找到对应的商品名称, goodsId:', data.value.goodsId)
        }
      }

      // 加载检验报告图片
      setTimeout(() => {
        loadInspectionImages()
      }, 500) // 延迟500ms确保DOM已渲染
    } else {
      console.warn('API响应状态异常或无数据')
    }
  } catch (error: any) {
    console.error('获取数据失败:', error)
    if (error?.response) {
      console.error('错误响应:', error.response.data)
      console.error('错误状态码:', error.response.status)
    }
  } finally {
    loading.value = false
  }
}

// 根据goodsId获取商品名称
const getGoodsName = (goodsId: number): string => {
  const good = goodsList.value.find(item => item.goodsId === goodsId)
  return good ? good.goodsName : goodsName.value || '未知商品'
}

// 打开修改对话框
const editProductionInfo = () => {
  if (!data.value) {
    ElMessage.warning('数据未加载完成')
    return
  }

  // 设置表单数据
  Object.assign(formData, data.value)

  // 设置图片预览 - 使用统一的图片URL处理函数
  if (data.value.coverImageUrl) {
    editForm.value.picture = getFullImageUrl(data.value.coverImageUrl);
    console.log('编辑表单图片预览URL:', editForm.value.picture);
  } else {
    editForm.value.picture = '';
  }

  // 获取商品列表并显示对话框
  getGoodsList().then(() => {
    showEditDialog.value = true
  })
}

// 导出溯源码功能
const exportTraceCode = async () => {
  if (!data.value || !data.value.id) {
    ElMessage.warning('数据不完整，无法导出')
    return
  }

  exportLoading.value = true

  try {
    console.log('开始导出溯源码，生产信息ID:', data.value.id)

    // 使用 /api/ProductionUpdate/{id} 接口获取详细的生产信息
    const productionUrl = `/api/ProductionUpdate/${data.value.id}`

    // 发送请求获取生产信息详情
    const response = await apiWreit.get(productionUrl, {
      headers: {
        'Accept': 'application/json'
      }
    })

    console.log('生产信息API响应:', response)

    if (response.status === 200 && response.data) {
      // 获取详细的生产信息数据
      const productionData = response.data.data || response.data
      console.log('获取到的生产信息详情:', productionData)

      // 生成文件名
      const currentGoodsName = getGoodsName(data.value.goodsId)
      const batchNumber = data.value.batchNumber || productionData.batchNumber || '未知批次'
      const filename = `${currentGoodsName}_${batchNumber}_溯源码.xlsx`

      // 创建Excel数据结构
      const excelData = [
        // 标题行
        ['溯源码信息表'],
        [''], // 空行

        // 基本信息部分
        ['基本信息'],
        ['商品名称', currentGoodsName],
        ['生产批次', batchNumber],
        ['生产信息ID', productionData.id || data.value.id],
        [''], // 空行

        // 生产详情部分
        ['生产详情'],
        ['保质期', `${productionData.shelfLifeDays || data.value.shelfLifeDays}天`],
        ['生产许可证号', productionData.productionLicenseNumber || data.value.productionLicenseNumber || '无'],
        ['生产企业', productionData.manufacturerName || data.value.manufacturerName || '无'],
        ['商品ID', productionData.goodsId || data.value.goodsId],
        [''], // 空行

        // 时间信息部分
        ['时间信息'],
        ['创建时间', productionData.createdTime || data.value.createdTime],
        ['修改时间', productionData.modifiedTime || data.value.modifiedTime || '无'],
        [''], // 空行

        // 图片信息部分
        ['图片信息'],
        ['封面图片', productionData.coverImageUrl ? getFullImageUrl(productionData.coverImageUrl) : '无'],
        [''], // 空行

        // 元数据部分
        ['生成信息'],
        ['生成时间', new Date().toLocaleString('zh-CN')],
        ['数据来源', `/api/ProductionUpdate/${data.value.id} API接口`]
      ]

      // 创建工作簿和工作表
      const workbook = XLSX.utils.book_new()
      const worksheet = XLSX.utils.aoa_to_sheet(excelData)

      // 设置列宽
      const columnWidths = [
        { wch: 15 }, // A列：标签列
        { wch: 30 }  // B列：数据列
      ]
      worksheet['!cols'] = columnWidths

      // 设置单元格样式（标题行）
      if (worksheet['A1']) {
        worksheet['A1'].s = {
          font: { bold: true, sz: 16 },
          alignment: { horizontal: 'center' }
        }
      }

      // 设置分类标题样式
      const categoryRows = [3, 8, 15, 19, 22] // 基本信息、生产详情、时间信息、图片信息、生成信息的行号
      categoryRows.forEach(row => {
        const cellRef = `A${row}`
        if (worksheet[cellRef]) {
          worksheet[cellRef].s = {
            font: { bold: true, sz: 12 },
            fill: { fgColor: { rgb: 'E6F3FF' } }
          }
        }
      })

      // 将工作表添加到工作簿
      XLSX.utils.book_append_sheet(workbook, worksheet, '溯源码信息')

      // 生成Excel文件并下载
      const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' })
      const blob = new Blob([excelBuffer], {
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      })

      const downloadUrl = window.URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = downloadUrl
      link.download = filename
      document.body.appendChild(link)
      link.click()

      // 清理
      document.body.removeChild(link)
      window.URL.revokeObjectURL(downloadUrl)

      ElMessage.success('Excel溯源码导出成功！')
      console.log('Excel文件下载完成:', filename)

    } else {
      throw new Error(`获取生产信息失败，服务器返回状态码: ${response.status}`)
    }
  } catch (error: any) {
    console.error('导出溯源码失败:', error)

    // 处理不同类型的错误
    let errorMessage = '导出失败'

    if (error.response) {
      // 服务器返回了错误响应
      if (error.response.status === 404) {
        errorMessage = '生产信息不存在或已被删除'
      } else if (error.response.status === 400) {
        errorMessage = '请求参数错误，请检查数据完整性'
      } else if (error.response.status === 500) {
        errorMessage = '服务器内部错误，请稍后重试'
      } else {
        errorMessage = `导出失败 (${error.response.status})`
      }
    } else if (error.request) {
      // 请求发送了但没有收到响应
      errorMessage = '网络连接失败，请检查网络状态'
    } else {
      // 其他错误
      errorMessage = error.message || '未知错误'
    }

    ElMessage.error(errorMessage)
  } finally {
    exportLoading.value = false
  }
}

// 获取完整图片URL的辅助函数
const getFullImageUrl = (imageUrl: string | null | undefined): string => {
  if (!imageUrl) return '';

  // 检查URL是否已经是完整的URL
  if (imageUrl.startsWith('http://') || imageUrl.startsWith('https://')) {
    return imageUrl;
  } else {
    // 如果是相对路径，则添加服务器地址
    return `http://localhost:34405${imageUrl}`;
  }
}

// 预加载图片函数（带缓存）
const preloadImage = (imageUrl: string): Promise<boolean> => {
  return new Promise((resolve) => {
    if (!imageUrl) {
      resolve(false);
      return;
    }

    // 检查缓存
    if (imageCache.has(imageUrl)) {
      console.log('图片已缓存:', imageUrl);
      resolve(imageCache.get(imageUrl) || false);
      return;
    }

    const img = new Image();
    img.onload = () => {
      console.log('图片预加载成功:', imageUrl);
      imageCache.set(imageUrl, true);
      resolve(true);
    };
    img.onerror = () => {
      console.error('图片预加载失败:', imageUrl);
      imageCache.set(imageUrl, false);
      resolve(false);
    };
    img.src = imageUrl;
  });
}

// 处理图片加载成功
const handleImageLoad = (event: Event) => {
  console.log('图片加载成功:', event)
  imageLoading.value = false
}

// 处理图片加载错误
const handleImageError = (event: Event) => {
  console.error('图片加载失败:', event)
  imageLoading.value = false
  const img = event.target as HTMLImageElement
  img.style.display = 'none'
}

// 获取上传时的额外数据（包含批次号和追溯阶段）
const getUploadData = () => {
  // 动态获取产品名称和检验报告标题
  const productName = data.value?.goodsName || '兔头 (麻辣味)'
  
  // 从DOM中获取检验报告标题
  const inspectionTitleElement = document.querySelector('.inspection-title')
  const inspectionTitle = inspectionTitleElement?.textContent || '产品检验报告'
  
  // 从DOM中获取产品标题
  const productTitleElement = document.querySelector('.product-name')
  const productTitle = productTitleElement?.textContent || productName
  
  console.log('上传数据 - 产品标题:', productTitle)
  console.log('上传数据 - 检验报告标题:', inspectionTitle)
  
  return {
    imageBatch: data.value?.batchNumber || '',
    traceStage: inspectionTitle, // 使用页面中的检验报告标题
    traceType: `${productTitle}_${inspectionTitle}` // 组合页面中的产品标题和检验报告标题
  }
}

// 检验报告图片上传前验证
const beforeInspectionUpload = (file: any) => {
  console.log('开始验证检验报告图片:', file)
  
  if (!file) {
    ElMessage.error('请选择要上传的文件!')
    return false
  }

  // 检查文件类型
  const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/bmp', 'image/webp']
  const isImage = allowedTypes.includes(file.type)
  if (!isImage) {
    ElMessage.error('只能上传JPG/PNG/GIF/BMP/WEBP格式的图片!')
    return false
  }

  // 检查文件大小（限制为10MB，检验报告可能较大）
  const maxSize = 10 * 1024 * 1024 // 10MB
  if (file.size > maxSize) {
    ElMessage.error('图片大小不能超过10MB!')
    return false
  }

  // 检查批次号
  if (!data.value?.batchNumber) {
    ElMessage.error('批次号不能为空，无法上传检验报告!')
    return false
  }

  // 打印即将上传的数据信息
  const uploadData = getUploadData()
  console.log('即将上传的数据:', uploadData)
  console.log('检验报告图片验证通过，批次号:', data.value.batchNumber)
  
  return true
}

// 处理检验报告图片上传成功
const handleInspectionImageSuccess = (response: any) => {
  console.log('检验报告图片上传响应:', response)
  
  if (response && response.data) {
    const imageData = response.data
    const fullImageUrl = getFullImageUrl(imageData.imagePath)
    
    // 获取当前的标题信息
    const inspectionTitleElement = document.querySelector('.inspection-title')
    const inspectionTitle = inspectionTitleElement?.textContent || '产品检验报告'
    
    const productTitleElement = document.querySelector('.product-name')
    const productTitle = productTitleElement?.textContent || data.value?.goodsName || '兔头 (麻辣味)'
    
    // 添加到检验报告图片列表
    inspectionImages.value.push({
      url: fullImageUrl,
      imageBatch: imageData.imageBatch || data.value?.batchNumber || '',
      traceStage: imageData.traceStage || inspectionTitle,
      traceType: imageData.traceType || `${productTitle}_${inspectionTitle}`
    })
    
    console.log('检验报告图片上传成功:', {
      url: fullImageUrl,
      batch: imageData.imageBatch,
      stage: imageData.traceStage,
      type: imageData.traceType
    })
    
    // 重置上传进度
    inspectionUploadProgress.value = 0
    
    ElMessage.success(`${inspectionTitle}上传成功!`)
  } else {
    console.error('检验报告上传失败，响应格式异常:', response)
    ElMessage.error('上传失败，未返回图片地址')
  }
}

// 处理检验报告图片上传进度
const handleInspectionUploadProgress = (event: any) => {
  if (event.percent !== undefined) {
    inspectionUploadProgress.value = Math.round(event.percent)
    console.log('检验报告上传进度:', inspectionUploadProgress.value + '%')
  }
}

// 处理检验报告图片上传错误
const handleInspectionImageError = (error: any) => {
  console.error('检验报告上传错误:', error)
  inspectionUploadProgress.value = 0
  ElMessage.error('检验报告上传失败，请检查网络或服务器状态')
}

// 移除检验报告图片
const removeInspectionImage = async (index: number) => {
  try {
    if (index < 0 || index >= inspectionImages.value.length) {
      ElMessage.error('图片索引无效')
      return
    }

    const imageToDelete = inspectionImages.value[index]
    if (!imageToDelete || !imageToDelete.url) {
      ElMessage.error('图片信息不完整，无法删除')
      return
    }

    // 从完整URL中提取imagePath
    let imagePath = imageToDelete.url
    if (imagePath.startsWith('http://localhost:34405')) {
      imagePath = imagePath.replace('http://localhost:34405', '')
    }

    console.log('准备删除检验报告图片:', {
      index: index,
      imagePath: imagePath,
      fullUrl: imageToDelete.url
    })

    // 调用删除API
    const response = await apiWreit.delete('/api/Image/delete-by-path', {
      params: {
        imagePath: imagePath
      },
      headers: {
        'Accept': 'text/plain'
      }
    })

    console.log('删除检验报告图片API响应:', response)

    if (response.status === 200) {
      // 从本地数组中移除图片
      inspectionImages.value.splice(index, 1)
      ElMessage.success('检验报告图片删除成功')
      console.log('检验报告图片删除成功，已从本地列表移除')
    } else {
      throw new Error('删除失败')
    }
  } catch (error: any) {
    console.error('删除检验报告图片失败:', error)
    if (error.response) {
      console.error('API响应错误:', error.response.data)
      ElMessage.error(`删除失败: ${error.response.data?.message || '未知错误'}`)
    } else {
      ElMessage.error('网络连接失败，请检查网络状态')
    }
  }
}

// 加载检验报告图片
const loadInspectionImages = async () => {
  if (!data.value?.batchNumber) {
    console.warn('批次号为空，无法查询检验报告图片')
    return
  }

  inspectionImagesLoading.value = true
  
  try {
    const inspectionTitleElement = document.querySelector('.inspection-title')
    const inspectionTitle = inspectionTitleElement?.textContent || '产品检验报告'
    
    const productTitleElement = document.querySelector('.product-name')
    const productTitle = productTitleElement?.textContent || data.value?.goodsName || '兔头 (麻辣味)'
    
    const traceStage = inspectionTitle
    const traceType = `${productTitle}_${inspectionTitle}`
    
    console.log('🔍 开始查询检验报告图片:')
    console.log('  - 批次号:', data.value.batchNumber)
    console.log('  - traceStage:', traceStage)
    console.log('  - traceType:', traceType)
    
    const response = await apiWreit.get('/api/Image/GetByCondition', {
      params: {
        imageBatch: data.value.batchNumber,
        traceStage: traceStage,
        traceType: traceType
      }
    })
    
    if (response.status === 200 && response.data) {
      const images = response.data.data || response.data || []
      
      const processedImages = images.map((image: any) => ({
        url: getFullImageUrl(image.imagePath),
        imageBatch: image.imageBatch || data.value.batchNumber,
        traceStage: image.traceStage || traceStage,
        traceType: image.traceType || traceType
      }))
      
      inspectionImages.value = processedImages
      
      console.log('✅ 检验报告图片查询成功:', processedImages.length, '张图片')
      console.log('图片列表:', processedImages)
      
      if (processedImages.length === 0) {
        console.log('📝 暂无检验报告图片')
      }
    } else {
      console.warn('查询检验报告图片响应异常:', response)
      inspectionImages.value = []
    }
  } catch (error: any) {
    console.error('❌ 查询检验报告图片失败:', error)
    inspectionImages.value = []
    
    if (error.response?.status === 404) {
      console.log('📝 未找到对应的检验报告图片')
    } else {
      ElMessage.error('查询检验报告图片失败')
    }
  } finally {
    inspectionImagesLoading.value = false
  }
}

// 监听数据变化，当批次号可用时加载检验报告图片
watch(() => data.value?.batchNumber, (newBatchNumber) => {
  if (newBatchNumber) {
    console.log('检测到批次号变化，准备加载检验报告图片:', newBatchNumber)
    setTimeout(() => {
      loadInspectionImages()
    }, 500)
  }
}, { immediate: false })

onMounted(() => {
  getProductionInfo()
})
</script>

<style scoped>
.trace-image-generator {
  width: 100%;
  padding: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f5f5;
}

.debug-info {
  background-color: #fff3cd;
  border: 1px solid #ffeaa7;
  border-radius: 4px;
  padding: 10px;
  margin-bottom: 20px;
  font-size: 14px;
  color: #856404;
}

.trace-card {
  width: 100%;
  max-width: 1200px;
  height: 400px;
  display: flex;
  overflow: hidden;
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  font-family: 'Microsoft YaHei', 'PingFang SC', sans-serif;
  margin: 0 auto;
  position: relative;
}

/* 养殖信息组件容器样式 */
.breeding-component-container {
  width: 100%;
  max-width: 1200px;
  margin: 20px auto;
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  padding: 20px;
  box-sizing: border-box;
}

.processing-info-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 300px;
  background-color: #f9f9f9;
  border-radius: 8px;
  color: #999;
}

.placeholder-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.placeholder-text {
  font-size: 16px;
}

/* 左侧产品图片区域 */
.product-image-section {
  width: 280px;
  height: 100%;
  background-color: #fafafa;
  display: flex;
  align-items: center;
  justify-content: center;
  border-right: 1px solid #e8e8e8;
  padding: 20px;
}

.product-image-wrapper {
  width: 240px;
  height: 240px;
  border-radius: 8px;
  overflow: hidden;
  background-color: #fff;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.15);
  position: relative;
}

.product-main-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.placeholder-image {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #f5f5f5;
  color: #999;
  font-size: 14px;
  gap: 8px;
}

.loading-spinner {
  font-size: 24px;
  animation: spin 1s linear infinite;
}

.no-image-icon {
  font-size: 48px;
  opacity: 0.5;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

/* 右侧信息区域 */
.product-info-section {
  flex: 1;
  padding: 20px 24px;
  display: flex;
  flex-direction: column;
  position: relative;
}

/* 右上角按钮区域 */
.top-actions {
  position: absolute;
  top: 16px;
  right: 16px;
  display: flex;
  gap: 8px;
}

.action-btn {
  padding: 6px 12px;
  font-size: 12px;
  border: 1px solid #d9d9d9;
  background-color: #f5f5f5;
  color: #666;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s;
  font-weight: normal;
}

.action-btn:hover {
  border-color: #1890ff;
  color: #1890ff;
  background-color: #e6f7ff;
}

.action-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

/* 产品标题区域 */
.product-title-section {
  margin-bottom: 24px;
  margin-top: 8px;
}

.product-name {
  font-size: 28px;
  font-weight: bold;
  color: #333;
  margin: 0;
  line-height: 1.2;
}

/* 信息网格布局 */
.product-info-grid {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 16px;
  margin-bottom: 24px;
}

.info-row {
  display: flex;
  gap: 60px;
}

.info-item {
  flex: 1;
  display: flex;
  align-items: center;
  font-size: 15px;
}

.info-item .label {
  color: #666;
  font-weight: normal;
  min-width: 120px;
}

.info-item .value {
  color: #333;
  font-weight: 500;
}

/* 检验报告区域 */
.inspection-section {
  margin-top: auto;
}

.inspection-header {
  margin-bottom: 12px;
}

.inspection-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.inspection-content {
  display: flex;
  align-items: center;
  gap: 16px;
  flex-wrap: wrap;
}

.inspection-document {
  width: 120px;
  height: 90px;
  border: 1px solid #ddd;
  border-radius: 8px;
  position: relative;
  background: #f9f9f9;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s, box-shadow 0.2s;
}

.inspection-document:hover {
  transform: scale(1.05);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
}

.document-preview {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}

.document-icon {
  font-size: 24px;
  color: #666;
}

.close-btn {
  position: absolute;
  top: -10px;
  right: -10px;
  width: 22px;
  height: 22px;
  background: #dc3545;
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  cursor: pointer;
  line-height: 1;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
  transition: all 0.2s;
}

.close-btn:hover {
  background: #c82333;
  transform: scale(1.1);
}

.add-document {
  width: 120px;
  height: 90px;
  border: 2px dashed #ccc;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s;
  background: #fafafa;
}

.add-document:hover {
  border-color: #1890ff;
  background: #e6f7ff;
  transform: scale(1.02);
}

.add-btn {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.plus-icon {
  font-size: 32px;
  color: #666;
  font-weight: bold;
  transition: color 0.3s;
}

.add-document:hover .plus-icon {
  color: #1890ff;
}

/* 信息徽章 */
.info-badge {
  width: 24px;
  height: 24px;
  background-color: #666;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.2s;
}

.info-badge:hover {
  background-color: #1890ff;
}

.badge-number {
  color: white;
  font-size: 12px;
  font-weight: bold;
}

/* 检验报告图片样式 */
.inspection-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 8px;
  transition: transform 0.2s;
}

.inspection-document:hover .inspection-image {
  transform: scale(1.02);
}

.inspection-upload {
  display: inline-block;
}

.upload-progress-mini {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
}

.progress-circle-mini {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background-color: #409eff;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  font-weight: 600;
  animation: pulse 1.5s ease-in-out infinite;
}

/* 底部导航 */
.bottom-navigation {
  width: 100%;
  max-width: 1200px;
  margin-top: 20px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.nav-tabs {
  display: flex;
  border-bottom: 1px solid #e8e8e8;
}

.nav-tab {
  flex: 1;
  padding: 12px 10px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  border-bottom: 3px solid transparent;
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 80px;
}



.nav-tab.active {
  background-color: #f0f8ff;
  border-bottom-color: #1890ff;
  animation: pulse-border 1.5s infinite;
}

.nav-tab.active .tab-text {
  color: #1890ff;
  font-weight: bold;
  animation: pulse-color 1.5s infinite;
}

.nav-tab:not(.active) {
  background-color: white;
}

.nav-tab:not(.active) .tab-text {
  color: #666;
}

@keyframes pulse-border {
  0% { border-bottom-color: #1890ff; }
  50% { border-bottom-color: #40a9ff; }
  100% { border-bottom-color: #1890ff; }
}

@keyframes pulse-color {
  0% { color: #1890ff; }
  50% { color: #40a9ff; }
  100% { color: #1890ff; }
}

.tab-text {
  font-size: 14px;
  transition: color 0.3s;
}

/* 对话框样式 */
.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.dialog-content {
  background-color: white;
  border-radius: 8px;
  width: 90%;
  max-width: 600px;
  max-height: 80vh;
  overflow-y: auto;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #e8e8e8;
}

.dialog-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.close-button {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #999;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.close-button:hover {
  color: #333;
}

.dialog-body {
  padding: 20px;
}

.form-row {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.form-label {
  width: 120px;
  font-size: 14px;
  color: #333;
  text-align: right;
  margin-right: 12px;
}

.required {
  color: #ff4d4f;
  margin-right: 4px;
}

.form-input {
  flex: 1;
}

.form-input input,
.form-select {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  font-size: 14px;
  transition: border-color 0.2s;
}

.form-input input:focus,
.form-select:focus {
  outline: none;
  border-color: #1890ff;
}

.dialog-footer {
  padding: 20px;
  border-top: 1px solid #e8e8e8;
  text-align: right;
}

.submit-button {
  background-color: #1890ff;
  color: white;
  border: none;
  padding: 8px 24px;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.submit-button:hover {
  background-color: #40a9ff;
}

.upload-demo {
  margin: 10px 0;
}

/* 图片上传样式 */
.image-upload-section {
  display: flex;
  margin-bottom: 24px;
  align-items: flex-start;
}

.image-upload-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.upload-placeholder {
  width: 150px;
  height: 150px;
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
  background-color: #fafafa;
}

.upload-placeholder:hover {
  border-color: #40a9ff;
  background-color: #e6f7ff;
}

.upload-icon {
  font-size: 48px;
  margin-bottom: 8px;
  color: #8c939d;
}

.upload-text {
  font-size: 14px;
  color: #606266;
  margin-bottom: 4px;
  font-weight: 500;
}

.upload-hint {
  font-size: 12px;
  color: #909399;
  text-align: center;
  line-height: 1.4;
}

.upload-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.upload-progress {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.progress-circle {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background-color: #409eff;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  font-weight: 600;
  margin-bottom: 8px;
  animation: pulse 1.5s ease-in-out infinite;
}

.progress-text {
  font-size: 14px;
  color: #409eff;
  font-weight: 500;
}

@keyframes pulse {
  0% { transform: scale(1); }
  50% { transform: scale(1.05); }
  100% { transform: scale(1); }
}

.image-preview {
  position: relative;
  width: 150px;
  height: 150px;
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.preview-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.image-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.image-preview:hover .image-overlay {
  opacity: 1;
}

.image-preview:hover .preview-image {
  transform: scale(1.05);
}

.change-text {
  color: white;
  font-size: 14px;
  font-weight: 500;
}

.image-info {
  margin-top: 12px;
  width: 100%;
  max-width: 400px;
}

.image-url {
  padding: 8px 12px;
  background-color: #f5f5f5;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
}

.url-label {
  font-size: 12px;
  color: #606266;
  font-weight: 500;
}

.url-link {
  font-size: 12px;
  color: #409eff;
  text-decoration: none;
  word-break: break-all;
  line-height: 1.4;
}

.url-link:hover {
  text-decoration: underline;
}

/* 检验报告图片加载状态 */
.inspection-loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 120px;
  height: 90px;
  background-color: #f8f9fa;
  border: 2px dashed #dee2e6;
  border-radius: 8px;
  color: #6c757d;
}

.inspection-loading .loading-spinner {
  font-size: 24px;
  margin-bottom: 8px;
  animation: spin 1s linear infinite;
}

.inspection-loading .loading-text {
  font-size: 12px;
  text-align: center;
  line-height: 1.2;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .trace-card {
    flex-direction: column;
    height: auto;
  }

  .product-image-section {
    width: 100%;
    height: 200px;
    border-right: none;
    border-bottom: 1px solid #e8e8e8;
  }

  .product-image-wrapper {
    width: 160px;
    height: 160px;
  }

  .info-row {
    flex-direction: column;
    gap: 12px;
  }

  .info-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }

  .info-item .label {
    min-width: auto;
  }

  .top-actions {
    position: static;
    margin-bottom: 16px;
    justify-content: center;
  }

  .nav-tabs {
    flex-direction: column;
  }

  .nav-tab {
    border-bottom: 1px solid #e8e8e8;
  }

  .nav-tab.active {
    border-bottom-color: #1890ff;
  }
}
</style>